<?php 
 //global $wpdb;
 
if ( version_compare( $GLOBALS['wp_version'], '3.6', '<' ) ) {
	require get_template_directory() . '/inc/back-compat.php';
}
if ( ! function_exists( 'gwp_setup' ) ) :
function gwp_setup() {
add_theme_support( 'post-thumbnails' );
set_post_thumbnail_size( 672, 372, true );
add_image_size( 'recent-thumbnails', 69, 75, true );
add_image_size( 'cover-thumbnails', 300, 350, true );
add_theme_support( 'html5', array(
		'search-form', 'comment-form', 'comment-list', 'gallery', 'caption'
	) );
add_theme_support( 'post-formats', array(
		'aside', 'image', 'video', 'audio', 'quote', 'link', 'gallery',
	) );
}
//remove admin bar
remove_action('init', 'wp_admin_bar_init');
add_filter( 'show_admin_bar', '__return_false' );

endif;
add_action( 'after_setup_theme', 'gwp_setup' );
ob_start();
function gwp_widgets_init() {
register_sidebar(array(
'name' => 'sidebar iklan atas', //nama sidebar
'id' => 'sidebar_iklan_atas', //id sidebar
'before_widget' => '<div class="col-md-12 column">', //tambahan tag div sebelum sidebar
'after_widget' => '</div>', //tutup tag sidebar div sebelum sidebar
'before_title' => '<h3>', //podo
'after_title' => '</h3>', //idem

));
register_sidebar(array(
'name' => 'sidebar iklan samping', //nama sidebar
'id' => 'sidebar_iklan_samping', //id sidebar
'before_widget' => '<div class="col-md-12 column"> ', //tambahan tag div sebelum sidebar
'after_widget' => '</div>', //tutup tag sidebar div sebelum sidebar
'before_title' => '<h3>', //podo
'after_title' => '</h3>', //idem

));
register_sidebar(array(
'name' => 'user favourite', //nama sidebar
'id' => 'sidebar_user_favourite', //id sidebar
'before_widget' => '', //tambahan tag div sebelum sidebar
'after_widget' => '', //tutup tag sidebar div sebelum sidebar
'before_title' => '', //podo
'after_title' => '', //idem

));
}
add_action( 'widgets_init', 'gwp_widgets_init' );

add_action('index.php','remove_template');



function my_front_end_login_fail( $username ) {
   $referrer = $_SERVER['HTTP_REFERER'];  // where did the post submission come from?
   if ($referrer == ( $referrer . '?login=failed' )){
   }
   // if there's a valid referrer, and it's not the default log-in screen
   if ( !empty($referrer) && !strstr($referrer,'wp-login') && !strstr($referrer,'wp-admin') ) {
     wp_redirect( $referrer . '?login=failed' );  // let's append some information (login=failed) to the URL for the theme to use
     }else {
	      	wp_redirect( $referrer ); exit;
   }
}
add_action( 'wp_login_failed', 'my_front_end_login_fail' );  // hook failed login
function alter_the_query( $request ) {
    $dummy_query = new WP_Query();  // the query isn't run if we don't pass any query vars
    $dummy_query->parse_query( $request );

    // this is the actual manipulation; do whatever you need here
    if ( $dummy_query->is_home() )
        $request['offset'] = 10;

    return $request;
}
//add_filter( 'request', 'alter_the_query' );
function  my_login_redirect( $redirect_to, $request, $user ) {
 $referrer = $_SERVER['HTTP_REFERER'];
   // is there a user to check?
    global $user;
   // if ( isset( $user->roles ) && is_array( $user->roles ) ) {
        //check for admins
     //   if ( in_array( 'administrator', $user->roles ) ) {
            // redirect them to the default place
       //     return home_url('/wp-admin/');
        //} else {
          //  return home_url();
       // }
    //} else {
       // return $redirect_to;
		return $referrer;
    //}
}

/*Login Error Handle*/


function aa_login_failed( $user ) {
    // check what page the login attempt is coming from
    $referrer = $_SERVER['HTTP_REFERER'];

    // check that were not on the default login page
    if ( !empty($referrer) && !strstr($referrer,'wp-login') && !strstr($referrer,'wp-admin') && $user!=null ) {
        // make sure we don't already have a failed login attempt
        if ( !strstr($referrer, '?login=failed' )) {
            // Redirect to the login page and append a querystring of login failed
            wp_redirect( $referrer . '?login=failed');
        } else {
            wp_redirect( $referrer );
        }

        exit;
    }
}
add_action( 'wp_login_failed', 'aa_login_failed' ); // hook failed login

/*Login Empty Fields Error handling*/
add_action( 'authenticate', 'pu_blank_login');

function pu_blank_login( $user ){
    // check what page the login attempt is coming from
    $referrer = $_SERVER['HTTP_REFERER'];

    $error = false;

    if($_POST['log'] == '' || $_POST['pwd'] == '')
    {
        $error = true;
    }

    // check that were not on the default login page
    if ( !empty($referrer) && !strstr($referrer,'wp-login') && !strstr($referrer,'wp-admin') && $error ) {

        // make sure we don't already have a failed login attempt
        if ( !strstr($referrer, '?login=failed') ) {
            // Redirect to the login page and append a querystring of login failed
            wp_redirect( $referrer . '?login=failed' );
        } else {
            wp_redirect( $referrer );
        }

    exit;

    }
}

/*Login Redirect*/
add_filter( 'login_redirect', 'my_login_redirect', 10, 3 );

/*Logout Redirect*/
function go_home(){
 $referrer = $_SERVER['HTTP_REFERER'];

    // check that were not on the default login page
  //  if ( !empty($referrer) && !strstr($referrer,'wp-login') && !strstr($referrer,'wp-admin') && $user!=null ) 
	//{
		//if ( !strstr($referrer, '?logout') ) {
            // Redirect to the login page and append a querystring of login failed
          //  wp_redirect( $referrer . '?logout' );
        //} else {
            wp_redirect( $referrer );
        //}
	//}
 // wp_redirect( home_url('/') );
  exit();
}
add_action('wp_logout','go_home');

//function restrict_admin()
//{	if ( ! current_user_can( 'manage_options' ) && '/wp-admin/admin-ajax.php' != $_SERVER['PHP_SELF'] ) {
  //              wp_redirect( site_url() );
//	}
//}
//add_action( 'admin_init', 'restrict_admin', 1 ); //administrator


function insert_attachment($file_handler,$post_id,$setthumb='false') {
	// check to make sure its a successful upload
	if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK) __return_false();

	require_once(ABSPATH . "wp-admin" . '/includes/image.php');
	require_once(ABSPATH . "wp-admin" . '/includes/file.php');
	require_once(ABSPATH . "wp-admin" . '/includes/media.php');

	$attach_id = media_handle_upload( $file_handler, $post_id );
	if ( is_wp_error( $attach_id ) ) {
		//echo "Gambar gagal di unggah! Pastikan ukuran dan besar gambar sudah tepat.";
		return 0;
	} else {
		// The image was uploaded successfully!
		if ($setthumb) update_post_meta($post_id,'_thumbnail_id',$attach_id);
		return $attach_id;
	}
	
}
function insert_thumbnails($file_handler,$post_id,$setthumb=true) {

// check to make sure its a successful upload
if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK) __return_false();

require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');

$attach_id = media_handle_upload( $file_handler, $post_id );

if ($setthumb) update_post_meta($post_id,'_thumbnail_id',$attach_id);
return $attach_id;
}


//pagination
function pagination($pages = '', $range = 4)
{  

     $showitems = ($range * 2)+1;  

     global $paged;
     if(empty($paged)) $paged = 1;

     if($pages == '')
     {
         global $wp_query;
         $pages = $wp_query->max_num_pages;
         if(!$pages)
         {
             $pages = 1;
         }
     }   

     if(1 != $pages)
     {
         echo "<div class=\"pagination\"><span>Page ".$paged." of ".$pages."</span>";
         if($paged > 2 && $paged > $range+1 && $showitems < $pages) echo "<a href='".get_pagenum_link(1)."'>&laquo; First</a>";
         if($paged > 1 && $showitems < $pages) echo "<a href='".get_pagenum_link($paged - 1)."'>&lsaquo; Previous</a>";

         for ($i=1; $i <= $pages; $i++)
         {
             if (1 != $pages &&( !($i >= $paged+$range+1 || $i <= $paged-$range-1) || $pages <= $showitems ))
             {
                 echo ($paged == $i)? "<span class=\"current\">".$i."</span>":"<a href='".get_pagenum_link($i)."' class=\"inactive\">".$i."</a>";
             }
         }

         if ($paged < $pages && $showitems < $pages) echo "<a href=\"".get_pagenum_link($paged + 1)."\">Next &rsaquo;</a>";  
         if ($paged < $pages-1 &&  $paged+$range-1 < $pages && $showitems < $pages) echo "<a href='".get_pagenum_link($pages)."'>Last &raquo;</a>";
         echo "</div>\n";
     }
}

function my_post_limit($limit) { 
	global $paged, $myOffset;
	if (empty($paged)) {
			$paged = 1;
	}
	$postperpage = intval(get_option('posts_per_page'));
	$pgstrt = ((intval($paged) -1) * $postperpage) + $myOffset . ', ';
	$limit = 'LIMIT '.$pgstrt.$postperpage;
	return $limit;
} //end function my_post_limit

//filter the time

function themeblvd_time_ago() {

	global $post;

	$date = get_the_modified_time('G', true, $post);

	/**
	 * Where you see 'themeblvd' below, you'd
	 * want to replace those with whatever term
	 * you're using in your theme to provide
	 * support for localization.
	 */ 

	// Array of time period chunks
	$chunks = array(
		array( 60 * 60 * 24 * 365 , __( 'tahun', 'themeblvd' ), __( 'tahun', 'themeblvd' ) ),
		array( 60 * 60 * 24 * 30 , __( 'bulan', 'themeblvd' ), __( 'bulan', 'themeblvd' ) ),
		array( 60 * 60 * 24 * 7, __( 'minggu', 'themeblvd' ), __( 'minggu', 'themeblvd' ) ),
		array( 60 * 60 * 24 , __( 'hari', 'themeblvd' ), __( 'hari', 'themeblvd' ) ),
		array( 60 * 60 , __( 'jam', 'themeblvd' ), __( 'jam', 'themeblvd' ) ),
		array( 60 , __( 'menit', 'themeblvd' ), __( 'menit', 'themeblvd' ) ),
		array( 1, __( 'detik', 'themeblvd' ), __( 'detik', 'themeblvd' ) )
	);

	if ( !is_numeric( $date ) ) {
		$time_chunks = explode( ':', str_replace( ' ', ':', $date ) );
		$date_chunks = explode( '-', str_replace( ' ', '-', $date ) );
		$date = gmmktime( (int)$time_chunks[1], (int)$time_chunks[2], (int)$time_chunks[3], (int)$date_chunks[1], (int)$date_chunks[2], (int)$date_chunks[0] );
	}

	$current_time = current_time( 'mysql', $gmt );
	$newer_date = ( !$newer_date ) ? strtotime( $current_time ) : $newer_date;

	// Difference in seconds
	$since = $newer_date - $date;

	// Something went wrong with date calculation and we ended up with a negative date.
	if ( 0 > $since )
		return __( 'sometime', 'themeblvd' );

	/**
	 * We only want to output one chunks of time here, eg:
	 * x years
	 * xx months
	 * so there's only one bit of calculation below:
	 */

	//Step one: the first chunk
	for ( $i = 0, $j = count($chunks); $i < $j; $i++) {
		$seconds = $chunks[$i][0];

		// Finding the biggest chunk (if the chunk fits, break)
		if ( ( $count = floor($since / $seconds) ) != 0 )
			break;
	}

	// Set output var
	$output = ( 1 == $count ) ? '1 '. $chunks[$i][1] : $count . ' ' . $chunks[$i][2];


	if ( !(int)trim($output) ){
		$output = '0 ' . __( 'seconds', 'themeblvd' );
	}

	$output .= __(' yang lalu', 'themeblvd');

	return $output;
}

// Filter our themeblvd_time_ago() function into WP's the_time() function
add_filter('the_modified_time', 'themeblvd_time_ago');

if ( !function_exists('wp_new_user_notification') ) {

    function wp_new_user_notification( $user_id, $plaintext_pass = '' ) {

        $user = new WP_User($user_id);



        $user_login = stripslashes($user->user_login);

        $user_email = stripslashes($user->user_email);



        $message  = sprintf(__('New user registration on your blog %s:'), get_option('blogname')) . "\r\n\r\n";

        $message .= sprintf(__('Username: %s'), $user_login) . "\r\n\r\n";

        $message .= sprintf(__('E-mail: %s'), $user_email) . "\r\n";



        @wp_mail(get_option('admin_email'), sprintf(__('[%s] New User Registration'), get_option('blogname')), $message);



        if ( empty($plaintext_pass) )

            return;



        $message  = __('Halo,') . "\r\n\r\n";

        $message .= sprintf(__("Terima kasih telah bergabung dengan %s! \nDi bawah ini adalah informasi untuk masuk :"), get_option('blogname')) . "\r\n\r\n";

        $message .= wp_login_url() . "\r\n";

        $message .= sprintf(__('Username: %s'), $user_login) . "\r\n";

        $message .= sprintf(__('Password: %s'), $plaintext_pass) . "\r\n\r\n";

        $message .= sprintf(__('Jika Anda mempunyai pertanyaan hubungi %s.'), get_option('admin_email')) . "\r\n\r\n";

        $message .= __('Selamat menulis!');



        wp_mail($user_email, sprintf(__('[%s] Your username and password'), get_option('blogname')), $message);



    }

}

function registration_process_hook() {
$new_user ;
	if (isset($_POST['adduser']) && isset($_POST['add-nonce']) && wp_verify_nonce($_POST['add-nonce'], 'add-user')) {
	
		// die if the nonce fails
		if ( !wp_verify_nonce($_POST['add-nonce'],'add-user') ) {
			wp_die('Sorry! That was secure, guess you\'re cheatin huh!');
		} else {
			// auto generate a password
			 $user_pass = wp_generate_password();
			// setup new user
			$emailconfirm = esc_attr( $_POST['emailconfirm'] );
			//$passwordconfirm = esc_attr( $_POST['passwordconfirm'] );
			$userdata = array(
				'user_pass' => $user_pass,
				'user_login' => esc_attr( $_POST['user_name'] ),
				'user_email' => esc_attr( $_POST['email'] ),
				'role' => get_option( 'default_role' ),
				'first_name' =>  esc_attr( $_POST['user_name'] )
			);
			// setup some error checks
			if ( !$userdata['user_login'] )
				$error = 'Username harus diisi!';
			elseif ( username_exists($userdata['user_login']) )
				$error = 'Maaf, username yang Anda masukkan sudah ada!';
			elseif ( !is_email($userdata['user_email'], true) )
				$error = 'Anda harus memasukkan alamat email yang valid!';
			elseif ( email_exists($userdata['user_email']) )
				$error = 'Maaf, email yang Anda masukkan sudah digunakan!';
			elseif ($userdata['user_email']!= $emailconfirm)
				$error = 'Maaf, email Anda tidak sama dengan email yang sebelumnya!';
			//elseif ($userdata['user_pass']!= $passwordconfirm)
				//$error = 'Maaf, password Anda tidak sama dengan password yang sebelumnya!';
			// setup new users and send notification
			else{
				$new_user = wp_insert_user( $userdata );
				wp_new_user_notification($new_user, $user_pass);
			}
		}
	}
	if ( $new_user ) : ?>

	<div id="login-error" style="background-color:#E0FFE0;border:1px solid green;padding:5px;"><!-- create and alert message to show successful registration -->
	<?php
		$user = get_user_by('id',$new_user);
		echo 'Terima kasih sudah mendaftar, <strong>' . $user->user_login .'</strong>!'; 
		echo '<br/>Mohon cek email Anda. Anda akan menerima password untuk masuk.<br/> (Cek juga folder spam Anda)';

	?>
	</div>
	
	<?php else : ?>
	
		<?php if ( $error ) : ?>
			<div id="login-error" style="background-color: #FFEBE8;border:1px solid #C00;padding:5px;"><p><!-- echo errors if users fails -->
				<?php echo $error; ?>
			</p></div>
		<?php endif; ?>
	
	<?php endif;

}
add_action('process_customer_registration_form', 'registration_process_hook');

function getNewMsgs($user_ID)
    {
     global $wpdb;
	 $feptable = $wpdb->prefix."fep_messages";
      $get_pms =  $wpdb->get_results($wpdb->prepare("SELECT id FROM ". $feptable . " WHERE (to_user = %d AND parent_id = 0 AND to_del = 0 AND status = 0 AND last_sender <> %d) OR (from_user = %d AND parent_id = 0 AND from_del = 0 AND status = 0 AND last_sender <> %d)", $user_ID, $user_ID, $user_ID, $user_ID));
      return $wpdb->num_rows;
    }
 function getPengumumanNum()
    {
      global $wpdb; //status = 2 indicates that the msg is an announcement :)
	   $feptable = $wpdb->prefix."fep_messages";
      $results = $wpdb->get_results("SELECT id FROM ". $feptable . " WHERE status = 2 ORDER BY id DESC");
      return $wpdb->num_rows;
    }
add_action( 'show_user_profile', 'my_show_extra_profile_fields' );
add_action( 'edit_user_profile', 'my_show_extra_profile_fields' );

function get_post_ (){
 $mydate=getdate(date("U"));
  $thismonth = $mydate["mon"];
  $thisyear = $mydate["year"];
global $wpdb;
 $datarating = array();
 $get_data = $wpdb -> get_results ("SELECT ID as postid FROM gra_posts
									WHERE `post_date`
									BETWEEN '".$thisyear."-".$thismonth."-01'
									AND '".$thisyear."-".$thismonth."-31' AND `post_parent` =0
									AND post_type='post' AND post_status='publish'");
foreach ($get_data as $data){
	$datapost[] = array("postid"=>(int)$data->postid);
}
return $datapost;
}
function get_datarating (){
 $mydate=getdate(date("U"));
  $thismonth = $mydate["mon"];
  $thisyear = $mydate["year"];
global $wpdb;
 $datarating = array();
 $get_data2 = $wpdb -> get_results ("SELECT post.post_author as authorid, post.ID as postid, post.post_title as title, postmeta.meta_value as rating FROM `gra_postmeta` AS postmeta 
									INNER JOIN gra_posts as post ON post.ID=postmeta.post_id
									WHERE post.`post_date`
									BETWEEN '".$thisyear."-".$thismonth."-01'
									AND '".$thisyear."-".$thismonth."-31' AND post.`post_parent` =0
									AND `meta_key` LIKE '%ratings_score%' ");
$postid=array();		
foreach ($get_data2 as $data){

	$rating = (int)$data->rating;
	$pid = (int)$data->postid;
	if (in_array((int)$data->postid, $postid)) 
	{
		foreach ($datarating as &$value){
		//if ($value['postid']== $pid){
		$value['value'] = $value['value'] + $rating;}
			// }
	}
	else {
		array_push($postid, (int)$data->postid);
		$datarating[] = array("postid"=>(int)$data->postid,"value"=>(int)$data->rating,"title"=>$data->title);
		}
}
array_sort_by_column($datarating, 'value');
return $datarating;
}

function get_datacomment(){
 $mydate=getdate(date("U"));
  $thismonth = $mydate["mon"];
   $thisyear = $mydate["year"];
global $wpdb;
 $datacomment = array();
$get_comment = $wpdb -> get_results ("SELECT post.ID as postid, comments.comment_ID as commentid, post.post_author as authorid,comments.user_id as comuserid
					FROM `gra_posts` AS post
					INNER JOIN gra_comments AS comments ON comments.comment_post_ID= post.`ID`
					WHERE post.`post_date`
					BETWEEN '".$thisyear."-".$thismonth."-01'
					AND '".$thisyear."-".$thismonth."-31'
					AND post.`post_parent` =0 
					AND comments.user_id not like post.post_author");
$postid=array();		
foreach ($get_comment as $data){

	if (in_array((int)$data->postid, $postid)) 
	{
		foreach ($datacomment as &$value){
		if ($data->postid==$value['postid']){
		   $value['comment'] = $value['comment'] + 5;
		   }
		 }
	}
	else {
		array_push($postid, (int)$data->postid);
		$datacomment[] = array("postid"=>(int)$data->postid,"comment"=>5);
		}
	}
//array_sort_by_column($datacomment, 'comment');
return $datacomment;
}

function get_dataviews(){
$mydate=getdate(date("U"));
  $thismonth = $mydate["mon"];
   $thisyear = $mydate["year"];
global $wpdb;
 $dataviews = array();
 $get_views = $wpdb -> get_results ("SELECT post.ID as postid, postmeta.meta_value as views FROM `gra_postmeta` AS postmeta 
									INNER JOIN gra_posts as post ON post.ID=postmeta.post_id
									WHERE post.`post_date`
									BETWEEN '".$thisyear."-".$thismonth."-01'
									AND '".$thisyear."-".$thismonth."-31' AND post.`post_parent` =0
									AND `meta_key` LIKE '%view%' ");
	
foreach ($get_views as $data){
	$dataviews[] = array("postid"=>(int)$data->postid,"views"=>((int)$data->views));
}
return $dataviews;
}

function get_popular_post_in_a_month($maxNumberofPost){
global $wpdb ;
 $mydate=getdate(date("U"));
  $thismonth = $mydate["mon"];
	//echo "$mydate[year]-$mydate[mon]-$mydate[mday]";
$datapost = get_post_();//postid
$datarating = get_datarating(); //postid, title, value
$datacomment = get_datacomment();// postid, count
$dataviews =get_dataviews(); //postid, views
$result = array();
foreach( $datapost as $keyA => $valA ) {
  foreach( $datarating as $keyB => $valB ) {
     if( $valA['postid'] == $valB['postid'] ) {
       $result[$keyA] = $valA + $valB;

       // or if you do not care output keys, just
       // $result[] = $valA + $valB;
     }
  }
}

foreach( $result as $keyA => $valA ) {
  foreach( $datacomment as $keyB => $valB ) {
     if( $valA['postid'] == $valB['postid'] ) {
       $result[$keyA] = $valA + $valB;

       // or if you do not care output keys, just
       // $result[] = $valA + $valB;
     }
  }
}
foreach( $result as $keyA => $valA ) {
  foreach( $dataviews as $keyB => $valB ) {
     if( $valA['postid'] == $valB['postid'] ) {
       $result[$keyA] = $valA + $valB;

       // or if you do not care output keys, just
       // $result[] = $valA + $valB;
     }
  }
}
foreach ($result as &$data){
$point = (($data['value']*0.5) + ($data['comment']*0.3) + ($data['views']*0.2));
$datagabung2[] = array('postid'=>(int)$data['postid'], 'point'=>$point);
$point = 0;
}
array_sort_by_column($datagabung2,'point');
for ($i=0; $i< $maxNumberofPost; $i++){

if ($datagabung2[$i]['point']==0){}
else {
echo "<div class='list-group-item' style='border-left:none; border-right:none;'><span class='badge'>poin : ".$datagabung2[$i]['point']."</span>";
echo "<a href='".get_permalink($datagabung2[$i]['postid'])."' class='colormenu'>&nbsp;&nbsp;". get_the_title( $datagabung2[$i]['postid'] )." </a>";
echo "</div>";	}
}
}					

function array_sort_by_column(&$arr, $col, $dir = SORT_DESC) {
    $sort_col = array();
    foreach ($arr as $key=> $row) {
        $sort_col[$key] = $row[$col];
    }

    array_multisort($sort_col, $dir, $arr);
}
function get_popular_author (){
 global $wpdb;
  $mydate=getdate(date("U"));
  $thismonth = $mydate["mon"];
   $thisyear = $mydate["year"];
	//echo "$mydate[year]-$mydate[mon]-$mydate[mday]";

 $totalrating = array();
 $author = array();
 //$authorlist = array($author, $postlist);
  $get_data2 = $wpdb -> get_results ("SELECT post.post_author as authorid, post.ID as postid, post.post_title as title, postmeta.meta_value as rating FROM `gra_postmeta` AS postmeta 
									INNER JOIN gra_posts as post ON post.ID=postmeta.post_id
									WHERE post.`post_date`
									BETWEEN '".$thisyear."-".$thismonth."-01'
									AND '".$thisyear."-".$thismonth."-31' AND post.`post_parent` =0
									AND `meta_key` LIKE '%ratings_score%' ");

$authorlist=array();		
foreach ($get_data2 as $data){

$rating = (int)$data->rating;
if (in_array((int)$data->authorid, $authorlist)) 
{
foreach ($datarating as &$value){
if ($value['authorid']== $data->authorid){
    $value['value'] = $value['value'] + $rating;}
	 }
}
else {
array_push($authorlist, (int)$data->authorid);
$datarating[] = array("postid"=>(int)$data->postid,"value"=>(int)$data->rating,"title"=>$data->title,"authorid"=>(int)$data->authorid);}
}
array_sort_by_column($datarating, 'value');

for ($i=0; $i< 10; $i++){
if ($datarating[$i]['value']==0||$datarating[$i]['authorid']==265){}//265=admin_GWP
else {

echo "<div class='list-group-item' style='border-left:none; border-right:none;'><span class='badge'>score : ".$datarating[$i]['value']."</span>";
echo "<a href='".get_author_posts_url( $datarating[$i]['authorid'] )."' class='colormenu'>&nbsp;&nbsp;". get_the_author_meta( 'first_name', $datarating[$i]['authorid'] )." ".get_the_author_meta( 'last_name', $datarating[$i]['authorid'] )."</a>";
echo "</div>";}}


}
function get_author_score($authorid){
global $wpdb;
  $mydate=getdate(date("U"));
  $thismonth = $mydate["mon"];
   $thisyear = $mydate["year"];
  $get_data = $wpdb -> get_results ("SELECT post.post_author as authorid,postmeta.meta_value as rating FROM `gra_postmeta` AS postmeta 
									INNER JOIN gra_posts as post ON post.ID=postmeta.post_id
									WHERE post.`post_date`
									BETWEEN '".$thisyear."-".$thismonth."-01'
									AND '".$thisyear."-".$thismonth."-31' AND post.`post_parent` =0
									AND `meta_key` LIKE '%ratings_score%' AND post_author='".$authorid."'");
foreach ($get_data as $data){
$rating += (int)$data->rating;
}
return $rating;
}
function get_post_point($postid){}
function show_count_favourite($userid){
global $wpdb;
$fav = 	$wpdb->get_var(
"SELECT count(*)
FROM gra_postmeta
WHERE meta_key='wpfp_favorites' AND meta_value LIKE '%".$userid."%'") ;
if($fav > 0){
	//echo '<div id="count">';
//					echo '<a class="wpfp-link" rel="nofollow" href="'.site_url().'?wpfpaction=add&postid='.get_the_ID().'">';
	//echo '+'.$fav;
	echo $fav;
	//echo '</a>';
	//echo '</div>';
}
else echo "0";

}
function my_show_extra_profile_fields( $user ) { ?>

	<h3>Extra profile information</h3>

	<table class="form-table">
	<tr>
			<th><label for="tempatlahir">Tempat Lahir</label></th>
			<td colspan="4">
				<input type="text" name="tempatlahir" id="tempatlahir" value="<?php echo esc_attr( get_the_author_meta( 'tempatlahir', $user->ID ) ); ?>" class="regular-text" /><br />
				<span class="description">Masukkan tempat lahir.</span>
			</td>
	</tr>
	<tr>
			<th><label for="tanggallahir">Tanggal Lahir</label></th>
			<td colspan="4">
				<input type="text" name="tanggallahir" id="tanggallahir" value="<?php echo esc_attr( get_the_author_meta( 'tanggallahir', $user->ID ) ); ?>" class="regular-text" /><br />
				<span class="description">Masukkan tanggal lahir.</span>
			</td>
	</tr>
		<tr>
			<th><label for="twitter">Twitter</label></th>

			<td colspan="4">
				<input type="text" name="twitter" id="twitter" value="<?php echo esc_attr( get_the_author_meta( 'twitter', $user->ID ) ); ?>" class="regular-text" /><br />
				<span class="description">Masukkan username Twitter.</span>
			</td>
		</tr>
		<tr>
			<th><label for="twitter">Jenis Kelamin</label></th>
			<?php $jk = esc_attr( get_the_author_meta( 'jk', $user->ID ) );  ?>
			<td><input type="radio" id="rdperempuan" value="Perempuan" name="rdjk" <?php echo ($jk=='Perempuan')?'checked':'' ?>>&nbsp;Perempuan</input> </td>
			<td><input type="radio" id="rdlaki" value="Laki-laki" name="rdjk" <?php echo ($jk=='Laki-laki')?'checked':'' ?>>&nbsp;Laki-laki</input></td>
			<td><input type="radio" id="rdlainnya" value="Lainnya" name="rdjk"<?php echo ($jk=='Lainnya')?'checked':'' ?>>&nbsp;Lainnya</input></td>
			<td><span class="description">Pilih jenis kelamin</span></td>
		</tr>
		<tr>
			<th><label for="twitter">Pekerjaan</label></th>
			<td colspan="4">
				<textarea name="pekerjaan" id="pekerjaan"><?php echo esc_attr( get_the_author_meta( 'pekerjaan', $user->ID ) ); ?></textarea><br />
				<span class="description">Masukkan pekerjaan.</span>
			</td>
		</tr>
		<tr>
			<th><label for="twitter">No. Telp</label></th>
			<td colspan="4">
				<input name="notelp" type = "text" id="notelp" value="<?php echo esc_attr( get_the_author_meta( 'notelp', $user->ID ) ); ?>" ></input><br />
				<span class="description">Masukkan No. Telp.</span>
			</td>
		</tr>
		
	</table>
<?php }
add_action( 'personal_options_update', 'my_save_extra_profile_fields' );
add_action( 'edit_user_profile_update', 'my_save_extra_profile_fields' );

function my_save_extra_profile_fields( $user_id ) {

	if ( !current_user_can( 'edit_user', $user_id ) )
		return false;

	/* Copy and paste this line for additional fields. Make sure to change 'twitter' to the field ID. */
	update_usermeta( $user_id, 'twitter', $_POST['twitter'] );
	update_usermeta( $user_id, 'jk', $_POST['rdjk'] );
	update_usermeta( $user_id, 'pekerjaan', $_POST['pekerjaan'] );
	update_usermeta( $user_id, 'notelp', $_POST['notelp'] );
	update_usermeta( $user_id, 'tempatlahir', $_POST['tempatlahir'] );
	update_usermeta( $user_id, 'tanggallahir', $_POST['tanggallahir'] );
}
// Redefine user notification function
function mytheme_comment($comment, $args, $depth) {
	$GLOBALS['comment'] = $comment;
	extract($args, EXTR_SKIP);

	if ( 'div' == $args['style'] ) {
		$tag = 'div';
		$add_below = 'coment';
	} else {
		$tag = 'li';
		$add_below = 'div-comment';
	} ?>
	 <div class="media"><?php echo "<a href=".get_author_posts_url($comment->user_id).">". get_the_author_meta( 'first_name', $comment->user_id )." ".get_the_author_meta( 'last_name', $comment->user_id)."</a>";?>
                         <a href="#" class="pull-left"><?php echo get_avatar( $comment, $args['avatar_size'] ); ?><!--<img src="img/foto suri.jpg" class="media-object fotocomment" />--></a>
                        <div class="media-body" style="padding-bottom:4px;">
                            <div class="coment" style="font-size:11.5px; color:#666;line-height: 20px; font-family: "Questrial",sans-serif;">
                           <?php comment_text();   $args=array('reply_text'=>'Balas','login_text'=>'Masuk untuk membalas');?>
						   	 <div style="float:right;font-size:11px;font-weight:bold; background-color:#f6af97; padding:5px; border: thin solid #ffe6e6; border-radius: 1em;"> <?php comment_reply_link( array_merge( $args, array( 'add_below' => 'coment', 'depth' => $depth, 'max_depth' => 2,'tag'=>'div' ) ) ); ?> </div>
                            </div>
                            <div class="font2"><?php echo get_comment_date().", ".get_comment_time()?> <!-- | <label>5 suka</label>&nbsp;|&nbsp;<span class="glyphicon glyphicon-heart-empty"></span> --></div>
                      	<!--	<div class="media">
                                 <a href="#" class="pull-left"><img src="img/foto suri.jpg" class="media-object fotocomment" /></a>
                                <div class="media-body coment">
                                    Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin commodo. Cras purus odio, vestibulum in vulputate at, tempus viverra turpis.
                                </div>
                                <div class="font2">19 jam lalu | <label>5 suka</label>&nbsp;|&nbsp;<span class="glyphicon glyphicon-heart-empty"></span></div>
                            </div> -->
                           
                        </div>
                    </div>
	
<?php
}
function new_excerpt_more( $more ) {
	return ' <a class="read-more" href="'. get_permalink( get_the_ID() ) . '">' . __('[Baca]', 'your-text-domain') . '</a>';
}
add_filter( 'excerpt_more', 'new_excerpt_more' );
function custom_excerpt_length( $length ) {
	return 25;
}
add_filter( 'excerpt_length', 'custom_excerpt_length', 999 );
function count_user_posts_by_status($post_status = 'publish',$user_id = 0){
    global $wpdb;
    $count = $wpdb->get_var(
        $wpdb->prepare( 
        "
        SELECT COUNT(ID) FROM $wpdb->posts 
        WHERE post_status = %s 
        AND post_author = %d",
        $post_status,
        $user_id
        )
    );
    return ($count) ? $count : 0;
}

?>
